package io.geekidea.springboot.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.geekidea.springboot.entity.Building;
import io.geekidea.springboot.exception.BusinessException;
import io.geekidea.springboot.mapper.BuildingMapper;
import io.geekidea.springboot.mapper.DeviceMapper;
import io.geekidea.springboot.service.IBuildingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BuildingServiceImpl extends ServiceImpl<BuildingMapper, Building> implements IBuildingService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public Page<Building> listByPage(int page, int size, List<Long> types) {
        Page<Building> pageInfo = new Page<>(page, size, true);
        return baseMapper.selectBuildingsWithType(pageInfo, types);
    }

    @Override
    public List<Building> getExportList(List<Long> types, List<Long> idList) {
        return baseMapper.selectExportBuildings(types, idList);
    }

    @Override
    public Building getById(Long id) {
        return baseMapper.selectBuildingWithId(id);
    }

    @Override
    public boolean delete(Long id) {
        //检查该设施下是否有设备
        int count = deviceMapper.countByBuildId(id);
        if (count > 0) {
            throw new BusinessException(400, "该设施下有设备，无法删除");
        }
        return super.removeById(id);
    }

    @Override
    public boolean save(Building building) {
        building.setCreatedAt(LocalDateTime.now());
        building.setUpdatedAt(LocalDateTime.now());
        return super.save(building);
    }

    @Override
    public boolean updateById(Building building) {
        building.setUpdatedAt(LocalDateTime.now());
        return super.updateById(building);
    }
}
